﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Text;
using System.Web.Script.Serialization;
using HtmlAgilityPack;

namespace xuptlibsearch
{
    public partial class Rank : System.Web.UI.Page
    {
        Dictionary<string, TypeDictItem> TypeDict = new Dictionary<string, TypeDictItem>();
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Charset = "UTF-8";
            Response.ContentType = "text/json";
            TypeDict.Add("1", new TypeDictItem { Name = "借阅排行榜", Code = "?type=circul.circulog_A&cname=½èÔÄÅÅÐÐ°ñ" });
            TypeDict.Add("2", new TypeDictItem { Name = "检索排行榜", Code = "?type=opac.n_search_log&cname=¼ìË÷ÅÅÐÐ°ñ" });
            TypeDict.Add("3", new TypeDictItem { Name = "收藏排行榜", Code = "?type=opac.n_collection&cname=ÊÕ²ØÅÅÐÐ°ñ" });
            TypeDict.Add("4", new TypeDictItem { Name = "书评排行榜", Code = "?type=opac.n_review&cname=ÊéÆÀÅÅÐÐ°ñ" });
            TypeDict.Add("5", new TypeDictItem { Name = "查看排行榜", Code = "?type=opac.n_look_log&cname=²é¿´ÅÅÐÐ°ñ" });
            TypeDict.Add("01", new TypeDictItem { Name = "借阅排行榜", Code = "?type=circul.circulog_A&cname=½èÔÄÅÅÐÐ°ñ" });
            TypeDict.Add("02", new TypeDictItem { Name = "检索排行榜", Code = "?type=opac.n_search_log&cname=¼ìË÷ÅÅÐÐ°ñ" });
            TypeDict.Add("03", new TypeDictItem { Name = "收藏排行榜", Code = "?type=opac.n_collection&cname=ÊÕ²ØÅÅÐÐ°ñ" });
            TypeDict.Add("04", new TypeDictItem { Name = "书评排行榜", Code = "?type=opac.n_review&cname=ÊéÆÀÅÅÐÐ°ñ" });
            TypeDict.Add("05", new TypeDictItem { Name = "查看排行榜", Code = "?type=opac.n_look_log&cname=²é¿´ÅÅÐÐ°ñ" });
            
            string type = Request.Params["type"];
            string size = Request.Params["size"];
            if ((type == null || type == "") || !typeAvaliable(type))
            {
                Response.Write("Type_Error");
                return;
            }
            if (size == null || size == "")
            {
                size = "10";
            }
            int s;
            try
            {
                s = Convert.ToInt32(size);
            }
            catch
            {
                s = 10;
            }
            ReqServer(type, s);
        }
        bool typeAvaliable(string type)
        {
            int i = 0;
            try
            {
                i = Convert.ToInt32(type);
            }
            catch
            {
                return false;
            }
            if (i < 1 || i > 5)
            {
                return false;
            }
            return true;
        }
        void ReqServer(string type, int size)
        {
            string restr = "";
            try
            {
                WebRequest request = WebRequest.Create("http://222.24.3.7:8080/opac_two/top/top_detail.jsp" + TypeDict[type].Code);
                WebResponse response = request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("GB2312"));
                restr = reader.ReadToEnd();
                switch (type)
                {
                    case "1": ProcRent(restr, size); break;
                    case "2": ProcSearch(restr, size); break;
                    case "3": ProcFav(restr, size); break;
                    case "4": Response.Write("null"); return;
                    case "5": ProcSee(restr, size); break;
                    case "01": ProcRent(restr, size); break;
                    case "02": ProcSearch(restr, size); break;
                    case "03": ProcFav(restr, size); break;
                    case "04": Response.Write("null"); return;
                    case "05": ProcSee(restr, size); break;
                }
            }
            catch
            {
                Response.Write("Server_Error");
                return;
            }

        }
        void ProcRent(string HTML,int s)
        {
            List<RentClass> Data = new List<RentClass>();
            HTML = HTML.Replace("\n", "");
            HTML = HTML.Replace("\r", "");
            HTML = HTML.Replace("\t", " ");
            HTML=HTML.Substring(HTML.IndexOf("<tr         class='td_color_1'         >"));
            string tmp = HTML.Substring(HTML.IndexOf("</table>"));
            HTML= HTML.Replace(tmp, "");
            HTML = HTML.Replace("         ", "");
            string[] t = Regex.Split(HTML, "</tr>");
            if (s > t.Length - 1)
            {
                Response.Write("Out_Of_Range");
                return;
            }
            HtmlDocument doc = new HtmlDocument();
            for (int i = 0; i < s ; i++)
            {
                doc.LoadHtml(t[i].Substring(48));
                HtmlNodeCollection ct = doc.DocumentNode.ChildNodes;
                HtmlNodeCollection node = ct[1].SelectNodes("//a[1]");
                string url = node[0].Attributes["href"].Value;
                url = url.Substring(url.IndexOf("sid=") + 4);
                string tt = url.Substring(url.IndexOf("&"));
                url = url.Replace(tt, "");
                string title = node[0].InnerText.Replace("&nbsp;", "");
                string sort = ct[3].InnerText;
                int times = Convert.ToInt32(ct[5].InnerText);
                Data.Add(new RentClass
                {
                    Rank = i + 1,
                    ID = url,
                    Title = title,
                    Times = times,
                    Sort = sort
                });
            }
            RentInfo rank = new RentInfo();
            rank.Amount = t.Length - 1;
            rank.Size = s;
            rank.Type = "借阅排行榜";
            rank.Item = Data;
            TransJSON(rank);
        }
        void TransJSON(object obj)
        {
            JavaScriptSerializer json = new JavaScriptSerializer();
            Response.Write(json.Serialize(obj));
        }
        void ProcSearch(string HTML, int s)
        {
            string str = HTML.Substring(HTML.IndexOf("<table border=0 width=812  valign=\"top\">"));
            string tmp = str.Substring(str.IndexOf("</form>"));
            str = str.Replace(tmp, "");
            str = str.Trim();
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(str);
            List<string> temp = new List<string>();
            foreach (var a in doc.DocumentNode.ChildNodes)
            {
                foreach (var b in a.ChildNodes)
                {
                    foreach (var c in b.ChildNodes)
                    {
                        string ttt = c.InnerText;
                        if (!(ttt.Contains("\n") && ttt.Contains("\r") && ttt.Contains("\t")))
                        {
                            temp.Add(ttt.Replace("&nbsp;",""));
                        }
                    }
                }
            }
            List<SearchItem> info = new List<SearchItem>();
            for (int i = 3; i < temp.Count; i += 3)
            {
                info.Add(new SearchItem
                {
                    Rank = Convert.ToInt32(temp[i]),
                    Keyword = Convert.ToString(temp[i + 1]),
                    Times = Convert.ToInt32(temp[i + 2])
                });
            }
            SearchInfo SearchData = new SearchInfo();
            SearchData.Amount = info.Count;
            SearchData.Item = SubList(info, s);
            if (SearchData.Item == null)
                return;
            SearchData.Size = s;
            SearchData.Type = "检索排行榜";
            TransJSON(SearchData);
        }
        List<SearchItem> SubList(List<SearchItem> L,int Len)
        {
            if (Len > L.Count || Len < 0)
            {
                Response.Write("Out_Of_Range");
                return null;
            }
            List<SearchItem> Temp = new List<SearchItem>();
            for (int i = 0; i < Len; i++)
            {
                Temp.Add(L[i]);
            }
            return Temp;
        }
        void ProcFav(string HTML, int s)
        {
            string str = HTML.Substring(HTML.IndexOf("<table border=0 width=812  valign=\"top\">"));
            string tmp = str.Substring(str.IndexOf("</form>"));
            str = str.Replace(tmp, "");
            str = str.Trim();
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(str);
            List<string> temp = new List<string>();
            foreach (var a in doc.DocumentNode.ChildNodes)
            {
                foreach (var b in a.ChildNodes)
                {
                    foreach (var c in b.ChildNodes)
                    {
                        string ttt = c.InnerText;
                        if (!(ttt.Contains("\n") && ttt.Contains("\r") && ttt.Contains("\t")))
                        {
                            temp.Add(ttt.Replace("&nbsp;", ""));
                            if (c.InnerHtml.Contains("href"))
                            {
                                string url = c.ChildNodes[0].Attributes[0].Value;
                                url = url.Replace("../search2/s_detail.jsp?sid=", "");
                                string tp = url.Substring(url.IndexOf("&"));
                                url = url.Replace(tp, "");
                                temp.Add(url);
                            }
                        }
                    }
                }
            }
            if(s>(temp.Count-3)/4)
            {
                Response.Write("Out_Of_Range");
                return;
            }
            List<FavItem> info = new List<FavItem>();
            for (int i = 3; i < s * 4; i += 4)
            {
                info.Add(new FavItem
                {
                    Rank = Convert.ToInt32(temp[i]),
                    Title = Convert.ToString(temp[i + 1]),
                    ID = Convert.ToString(temp[i + 2]),
                    Times = Convert.ToInt32(temp[i + 3])
                });
            }
            FavInfo Fav = new FavInfo();
            Fav.Amount = (temp.Count - 3) / 4;
            Fav.Item = info;
            Fav.Size = s;
            Fav.Type = "收藏排行榜";
            TransJSON(Fav);
        }
        void ProcSee(string HTML, int s)
        {
            string str = HTML.Substring(HTML.IndexOf("<table border=0 width=812  valign=\"top\">"));
            string tmp = str.Substring(str.IndexOf("</form>"));
            str = str.Replace(tmp, "");
            str = str.Trim();
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(str);
            List<string> temp = new List<string>();
            foreach (var a in doc.DocumentNode.ChildNodes)
            {
                foreach (var b in a.ChildNodes)
                {
                    foreach (var c in b.ChildNodes)
                    {
                        string ttt = c.InnerText;
                        if (!(ttt.Contains("\n") && ttt.Contains("\r") && ttt.Contains("\t")))
                        {
                            temp.Add(ttt.Replace("&nbsp;", ""));
                            if (c.InnerHtml.Contains("href"))
                            {
                                string url = c.ChildNodes[0].Attributes[0].Value;
                                url = url.Replace("../search2/s_detail.jsp?sid=", "");
                                string tp = url.Substring(url.IndexOf("&"));
                                url = url.Replace(tp, "");
                                temp.Add(url);
                            }
                        }
                    }
                }
            }
            if (s > (temp.Count - 3) / 4)
            {
                Response.Write("Out_Of_Range");
                return;
            }
            List<FavItem> info = new List<FavItem>();
            for (int i = 3; i < s * 4; i += 4)
            {
                info.Add(new FavItem
                {
                    Rank = Convert.ToInt32(temp[i]),
                    Title = Convert.ToString(temp[i + 1]),
                    ID = Convert.ToString(temp[i + 2]),
                    Times = Convert.ToInt32(temp[i + 3])
                });
            }
            FavInfo Fav = new FavInfo();
            Fav.Amount = (temp.Count - 3) / 4;
            Fav.Item = info;
            Fav.Size = s;
            Fav.Type = "查看排行榜";
            TransJSON(Fav);
        }
    }
}